// new People('whr').sleep(3).eat('apple').sleep(5).eat('durian')

class People {
  constructor(name) {
    this.name = name;
    this.sayHello();
    this.queue = Promise.resolve();
  }
  sayHello() {
    console.log(`hello, ${this.name}`);
  }
  sleep(time) {
    this.queue = this.queue.then(() => {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve();
        }, time * 1000)
      })
    })
    return this;
  }
  eat(food) {
    this.queue = this.queue.then(() => {
      console.log(`${this.name} eat ${food}`);
    })
    return this;
  }
}

new People('whr').sleep(3).eat('apple').sleep(5).eat('durian')

class People {
  constructor(name) {
    this.name = name;
    this.sayHello();
    this.queue = [];
    this.index = 0;
  }
  sayHello() {
    console.log(`hello, ${this.name}`);
  }
  sleep(time) {
    this.queue.push(() => {
      setTimeout(() => {
        this.run();
      }, time * 1000)
    })
    return this;
  }
  eat(food) {
    this.queue.push(() => {
      console.log(`${this.name} eat ${food}`);
      this.run();
    })
    return this;
  }
  async run() {
    const fn = this.queue[this.index];
    this.index++;
    if (typeof fn === 'function') {
      fn();
    }
  }
}

new People('whr').sleep(3).eat('apple').sleep(5).eat('durian');